<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24" class="mb-[12px]">
        <el-card style="min-width: 480px">
          <template #header>
            <div class="card-header">
              <span>需求发起</span>
            </div>
          </template>

          <el-form
            ref="requirementFormRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" />
            </el-form-item>

            <el-form-item label="需求描述" prop="description">
              <el-input v-model="formData.description" :rows="5" type="textarea" placeholder="请输入内容" />
            </el-form-item>

            <el-form-item label="附件" prop="attachments">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="/api/bus/upload/uploadFiles"
                multiple
                :on-remove="handleRemove"
                :limit="3"
                :on-success="handleFileSuccess"
                :before-upload="beforeFileUpload"
              >
                <el-button type="primary">上传附件</el-button>

              </el-upload>
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">提 交</el-button>
              <el-button type="primary" @click="handleSave">暂 存</el-button>
            </div>
          </template>
        </el-card>

        <!-- 流程设置弹窗 -->
        <el-dialog
          v-model="workNodesVisible"
          title="流程配置"
          width="550px"
          @close="handleCloseDialog"
        >
          <el-table
            ref="workNodesRef"
            v-loading="loading"
            :data="workNodeList"
            highlight-current-row
            border
          >
            <el-table-column label="节点名称" prop="nodeName" min-width="120" />
            <el-table-column label="处理人" prop="userId" min-width="150" >
              <template #default="{ row }">
                <el-select placeholder="请选择处理人" v-model="row.userId" filterable>
                  <el-option
                  value="0"
                  label="请选择"/>
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" prop="inuse" width="150" >
              <template #default="{ row }">
                <el-radio-group v-model="row.inuse">
                  <el-radio value="1">是</el-radio>
                  <el-radio value="0">否</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
          </el-table>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="handleSubmit">确 定</el-button>
              <el-button @click="handleCloseDialog">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "RequirementApply",
  inheritAttrs: false,
});

import RequirementAPI, { RequirementData } from "@/api/requirement";
import UserAPI from "@/api/user";
import router from "@/router";

const route = useRoute();
const requirementFormRef = ref(ElForm);
// 实例节点设置相关
const workNodesVisible = ref(false);
const workNodesRef = ref(ElForm);
const workNodeList = ref([]);
const userList = ref([]);

// 需求表单
const formData = reactive<RequirementData>({
  id: null,
  title: '',
  description: '',
  attachments: '',
  processId: 0,
  workNodes: '',
});
const rules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" },{ min: 1, max: 256, message: '输入长度在 1 到 256 个字符', trigger: 'blur' }],
  description: [{ required: true, message: "请输入需求描述", trigger: "blur" },{ min: 1, max: 512, message: '输入长度在 1 到 512 个字符', trigger: 'blur' }],
});

const fileList = ref<UploadUserFile[]>([])
const handleFileSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.attachments = response.data
}
const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }
  return true
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  // console.log(file, uploadFiles)
}

const loading = ref(false);
/** 提交需求表单 */
const submitForm = () => {
  if (route.query.workId){ // 流程已启动，直接提交
    handleSubmit();
  }
  else{ // 流程未启动，启动实例节点配置
    workNodesVisible.value = true;
  }
}
const handleSubmit = () => {
  requirementFormRef.value.validate((valid: any) => {
    if (valid) {
      // 处理附件
      let files = [];
      for(let i = 0; i < fileList.value.length; i++){
        if (fileList.value[i].response){
          files.push(fileList.value[i].response.data[0])
        }
        else{
          let fileJson = {};
          fileJson.name = fileList.value[i].name;
          fileJson.url = fileList.value[i].url;
          files.push(fileJson);
        }
      }
      formData.attachments = JSON.stringify(files);
      // 处理节点配置
      if (!route.query.workId){
        let nodes = [];
        let counter = 0;
        for(let i in workNodeList.value ){
          let workNode = workNodeList.value[i];
          let tmp = [workNode.nodeId, workNode.userId, workNode.inuse];
          nodes.push(tmp.join(","));
          if (workNode.inuse == "0"){
            counter++;
          }
        }
        // 不允许全部审批节点禁用
        if (counter == workNodeList.value.length){
          ElMessage.warning("不允许禁用所有节点");
          return;
        }
        formData.workNodes = nodes.join(";");
      }
      loading.value = true;
      RequirementAPI.apply(formData)
          .then((data) => {
            ElMessage.success(data.msg);
            ElMessage.success(data.data);
            router.push({ path: '/requirement/view' });
          })
          .finally(() => (loading.value = false));
    }
  });
}

/** 保存需求表单 */
const handleSave = () => {
  requirementFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      // 处理附件
      let files = [];
      for(let i = 0; i < fileList.value.length; i++){
        if (fileList.value[i].response){
          files.push(fileList.value[i].response.data[0])
        }
        else{
          let fileJson = {};
          fileJson.name = fileList.value[i].name;
          fileJson.url = fileList.value[i].url;
          files.push(fileJson);
        }
      }
      formData.attachments = JSON.stringify(files);
      RequirementAPI.save(formData)
          .then(({data}) => {
            formData.id = data; // id回写
            ElMessage.success("暂存成功");
          })
          .finally(() => (loading.value = false));
    }
  });
}

function handleCloseDialog(){
  workNodesVisible.value = false;
}

onMounted(() => {
  if (route.query.id){
    RequirementAPI.getById(route.query.id).then(({data}) => {
      if (data){
        formData.id = data.id;
        formData.title = data.title;
        formData.description = data.description;
        formData.attachments = data.attachments;
        if (formData.attachments){
          let files = JSON.parse(formData.attachments);
          for(let i = 0; i < files.length; i++){
            fileList.value.push({name: files[i]["name"], url: files[i]["url"]});
          }
        }
      }
    })
  }
  else if (route.query.workId){
    RequirementAPI.getByWorkId(route.query.workId).then(({data}) => {
      if (data){
        formData.id = data.id;
        formData.title = data.title;
        formData.description = data.description;
        formData.attachments = data.attachments;
        if (formData.attachments){
          let files = JSON.parse(formData.attachments);
          for(let i = 0; i < files.length; i++){
            fileList.value.push({name: files[i]["name"], url: files[i]["url"]});
          }
        }
      }
    })
  }

  if (route.query.processId) {
    formData.processId = route.query.processId;
  }

  RequirementAPI.getFlowNodes().then(({data}) => {
    if (data){
      for (let i in data){
        workNodeList.value.push({nodeId: data[i].nodeId, userId: "0", inuse: "1", nodeName: data[i].nodeName })
      }
    }
  })
  // 获取用户列表
  UserAPI.getUserList()
  .then(({data}) => {
    userList.value = data;
  })
});
</script>
